//引入User对象
var User = require('../models/user');
//引入Post对象
var Post = require('../models/post');
Comment = require('../models/comment.js');
//引入密码的第三方模块
var crypto = require('crypto');

//权限的判断
//如果用户没有登录。则不能访问发表和退出页面
function checkLogin(req,res,next) {
  if(!req.session.user){
    req.flash('error','未登录');
    res.redirect('/login')
  }
  next();
}
//如果用户登录了，则不能访问登录了注册页面
function checkNotLogin(req,res,next) {
  if (req.session.user){
    req.flash('success','已经登录了');
    res.redirect('/');
  }
  next();
}
module.exports = function (app) {
  //所有的路由操作都会写在这里，·····

  //首页
  app.get('/', function (req, res) {
    //判断是否是第一页，并把请求的页数转换成 number 类型
    var page = req.query.p ? parseInt(req.query.p) : 1;
    //查询并返回第 page 页的 10 篇文章
    Post.getTen(null, page, function (err, posts, total) {
      if (err) {
        posts = [];
      }
      res.render('index', {
        title: '主页',
        posts: posts,
        page: page,
        isFirstPage: (page - 1) == 0,
        isLastPage: ((page - 1) * 10 + posts.length) == total,
        user: req.session.user,
        success: req.flash('success').toString(),
        error: req.flash('error').toString()
      });
    });
  });
  //注册页面
  app.get('/reg', checkNotLogin);
  app.get('/reg',function (req,res) {
    res.render('reg',{
      title:'注册',
      user:req.session.user,
      success:req.flash('success').toString(),
      error:req.flash('error').toString()
    })
  });
  //注册行为
  app.post('/reg', checkNotLogin);
  app.post('/reg',function (req,res) {
    //1.收集数据
    //2.判断两次输入的密码是否一样
    //3.对密码进行加密
    //4.最后将收集好的数据整理完毕
    //5.判断用户名是否存在
    //6.如果不存在，说明可以进行操作，那么就开始新增用户操作
    //7.新增后，将用户信息放入session当中，
    var name = req.body.name;
    var password = req.body.password;
    var password_re =req.body['password-repeat'];
    if(password != password_re){
      req.flash('error','两次输入密码不一致');
      return res.redirect('/reg');
    }
    var md5 = crypto.createHash
    ('md5');
    var password = md5.update(req.body.password).digest('hex');

    var newUser = new User({
      name:name,
      password:password,
      email:req.body.email
    });

    User.get(newUser.name,function (err,user) {
      if(err){
        req.flash('error',err);
        return res.redirect('/reg')
      }
      if(user){
        req.flash('error','用户名已存在');
        return res.redirect('/reg')
      }
      newUser.save(function (err,user) {
        if(err){
          req.flash('error',err);
          return res.redirect('/reg')
        }
        req.session.user = newUser;
        req.flash('success','注册成功');
        res.redirect('/')
      })
    })
  });
  app.get('/upload', checkLogin);
  app.get('/upload', function (req, res) {
    res.render('upload', {
      title: '文件上传',
      user: req.session.user,
      success: req.flash('success').toString(),
      error: req.flash('error').toString()
    });
  });
  app.post('/upload', checkLogin);
  app.post('/upload', function (req, res) {
    req.flash('success', '文件上传成功!');
    res.redirect('/upload');
  });
  //登录页面
  app.get('/login', checkNotLogin);
  app.get('/login',function (req,res) {
    res.render('login',{
      title:'登录',
      user:req.session.user,
      success:req.flash('success').toString(),
      error:req.flash('error').toString()
    })
  });
  app.post('/login', checkNotLogin);
  app.post('/login',function (req,res) {
    //1.首先先生成密码的md5值
    //2.判断一下用户是否存在
    //3.判断一下密码是否正确
    //4.将登录的用户的信息存入session，然后跳转到首页
    var md5 = crypto.createHash('md5');
    var password = md5.update(req.body.password).digest('hex');
    User.get(req.body.name,function (err,user) {
      if(err){
        req.flash('error','用户名已经存在');
        return res.redirect('/login')
      }
      if (!user) {
        //用户不存在的时候
        req.flash('error', '用户不存在!');
        return res.redirect('/login');
      }
      if(user.password != password){
        req.flash('error','密码错误');
        return res.redirect('/login')
      }
      req.session.user = user;
      req.flash('success','登录成功');
      res.redirect('/');
    })
  });
  //退出
  app.get('/logout', checkLogin);
  app.get('/logout',function (req,res) {
    //删除session的时候，一定要删除session里某个值
    req.session.user = null;
    req.flash('success','退出成功');
    res.redirect('/');
  });
  app.get('/u/:name', function (req, res) {
    var page = req.query.p ? parseInt(req.query.p) : 1;
    //检查用户是否存在
    User.get(req.params.name, function (err, user) {
      if (!user) {
        req.flash('error', '用户不存在!');
        return res.redirect('/');
      }
      //查询并返回该用户第 page 页的 10 篇文章
      Post.getTen(user.name, page, function (err, posts, total) {
        if (err) {
          req.flash('error', err);
          return res.redirect('/');
        }
        res.render('user', {
          title: user.name,
          posts: posts,
          page: page,
          isFirstPage: (page - 1) == 0,
          isLastPage: ((page - 1) * 10 + posts.length) == total,
          user: req.session.user,
          success: req.flash('success').toString(),
          error: req.flash('error').toString()
        });
      });
    });
  });
  app.get('/u/:name/:day/:title', function (req, res) {
    Post.getOne(req.params.name, req.params.day, req.params.title, function (err, post) {
      if (err) {
        req.flash('error', err);
        return res.redirect('/');
      }
      res.render('article', {
        title: req.params.title,
        post: post,
        user: req.session.user,
        success: req.flash('success').toString(),
        error: req.flash('error').toString()
      });
    });
  });
  app.get('/edit/:name/:day/:title', checkLogin);
  app.get('/edit/:name/:day/:title', function (req, res) {
    var currentUser = req.session.user;
    Post.edit(currentUser.name, req.params.day, req.params.title, function (err, post) {
      if (err) {
        req.flash('error', err);
        return res.redirect('back');
      }
      res.render('edit', {
        title: '编辑',
        post: post,
        user: req.session.user,
        success: req.flash('success').toString(),
        error: req.flash('error').toString()
      });
    });
  });
  app.post('/edit/:name/:day/:title', checkLogin);
  app.post('/edit/:name/:day/:title', function (req, res) {
    var currentUser = req.session.user;
    Post.update(currentUser.name, req.params.day, req.params.title, req.body.post, function (err) {
      var url = encodeURI('/u/' + req.params.name + '/' + req.params.day + '/' + req.params.title);
      if (err) {
        req.flash('error', err);
        return res.redirect(url);//出错！返回文章页
      }
      req.flash('success', '修改成功!');
      res.redirect(url);//成功！返回文章页
    });
  });
  app.get('/remove/:name/:day/:title', checkLogin);
  app.get('/remove/:name/:day/:title', function (req, res) {
    var currentUser = req.session.user;
    Post.remove(currentUser.name, req.params.day, req.params.title, function (err) {
      if (err) {
        req.flash('error', err);
        return res.redirect('back');
      }
      req.flash('success', '删除成功!');
      res.redirect('/');
    });
  });
  app.post('/u/:name/:day/:title', function (req, res) {
    var date = new Date(),
        time = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " " +
            date.getHours() + ":" + (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes());
    var comment = {
      name: req.body.name,
      email: req.body.email,
      website: req.body.website,
      time: time,
      content: req.body.content
    };
    var newComment = new Comment(req.params.name, req.params.day, req.params.title, comment);
    newComment.save(function (err) {
      if (err) {
        req.flash('error', err);
        return res.redirect('back');
      }
      req.flash('success', '留言成功!');
      res.redirect('back');
    });
  });
  //发表
  app.get('/post', checkLogin);
  app.get('/post',function (req,res) {
    res.render('post', {
      title: '发表',
      user: req.session.user,
      success: req.flash('success').toString(),
      error: req.flash('error').toString()
    });
  });
  app.post('/post', checkLogin);
  app.post('/post',function (req,res) {
    //1.数据收集
    //2.数据保存
    //3.跳转到首页
    var currentUser = req.session.user.name;
    var post = new Post(currentUser,req.body.title,req.body.post);
    post.save(function (err) {
      if (err) {
        req.flash('error', err);
        return res.redirect('/');
      }


      req.flash('success', '发布成功!');
      res.redirect('/');//发表成功跳转到主页
    })

  });
  app.get('/archive', function (req, res) {
    Post.getArchive(function (err, posts) {
      if (err) {
        req.flash('error', err);
        return res.redirect('/');
      }
      res.render('archive', {
        title: '存档',
        posts: posts,
        user: req.session.user,
        success: req.flash('success').toString(),
        error: req.flash('error').toString()
      });
    });
  });
};


